package top.h1234.web;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import top.h1234.mapper.UserMapper;
import top.h1234.pojo.User;
import top.h1234.util.SqlSessionFactoryUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1. 获取登录的用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 2. 调用MyBatis
        // 2.1 加载mybatis核心配置文件，获取 sqlSessionFactory
        /*String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

        // 2.2 获取SqlSession对象，用于执行sql语句
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 2.3 获取UserMapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        // 2.4 执行sql
        User user = userMapper.select(username, password);

        // 2.5 释放资源
        sqlSession.close();

        // 设置响应字符格式及编码（防止中文乱码现象）
        response.setContentType("text/html;charset=utf-8");
        // 获取字符输出流
        PrintWriter writer = response.getWriter();

        // 3. 判断用户是否存在
        if (user != null) {
            // 用户存在，登录成功
            writer.write("登录成功！");
        } else {
            // 用户不存在，登录失败
            writer.write("登录失败！");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doGet(request, response);
    }
}
